package io.persimmon.core.module.trace;

import org.apache.commons.collections4.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

public class TraceManager {
    private static final ThreadLocal<List<TraceContext>> threadLocal = new ThreadLocal<>();

    public static TraceContext createTrace(String name) {
        List<TraceContext> traceContextList = threadLocal.get();
        TraceContext traceContext = new TraceContext(name);
        if (Objects.isNull(traceContextList)) {
            traceContextList = new ArrayList<>();
            traceContextList.add(traceContext);
            threadLocal.set(traceContextList);
        } else {
            traceContextList.add(traceContext);
        }
        return traceContext;
    }

    public static List<TraceContext> currentTraces() {
        return Optional.ofNullable(threadLocal.get()).orElse(new ArrayList<>());
    }

    public static boolean hasTrace() {
        return CollectionUtils.isNotEmpty(currentTraces());
    }

    public static void removeAllTrace() {
        threadLocal.remove();
    }

    public static void removeTrace(TraceContext traceContext) {
        currentTraces().remove(traceContext);
        if (CollectionUtils.isEmpty(currentTraces())) {
            removeAllTrace();
        }
    }
}
